﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace App25
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void AddYellow(object sender, RoutedEventArgs e)
        { Add(new SolidColorBrush(Colors.Yellow)); }

        private void AddRed(object sender, RoutedEventArgs e)
        { Add(new SolidColorBrush(Colors.Red)); }

        private void AddBlue(object sender, RoutedEventArgs e)
        { Add(new SolidColorBrush(Colors.Blue)); }

        private void Add(SolidColorBrush brush)
        {
            var ornament = new Ellipse
            {
                Height = 50,
                Width = 50,
                Fill = brush,
                RenderTransform = new CompositeTransform(),
            };
            TreeContainer.Children.Add(ornament);
            ornament.ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY;
            ornament.ManipulationDelta += (s, e) =>
            {
                var t = ornament.RenderTransform as CompositeTransform;
                t.TranslateX += e.Delta.Translation.X;
                t.TranslateY += e.Delta.Translation.Y;
            };
        }

        private async void Snapshot(object sender, RoutedEventArgs e)
        {
            await CaptureAndSave(TreeContainer);
        }

        async System.Threading.Tasks.Task<Windows.Storage.StorageFile> CaptureAndSave(UIElement element)
        {
            // capture
            var bitmap = new Windows.UI.Xaml.Media.Imaging.RenderTargetBitmap();
            await bitmap.RenderAsync(element);
            var picker = new Windows.Storage.Pickers.FileSavePicker
            {
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary,
                FileTypeChoices = { { "JPEG", new[] { ".jpg" } } },
                SuggestedFileName = "Image",
                DefaultFileExtension = ".jpg",
                CommitButtonText = "Save",
            };

            // save
            var file = await picker.PickSaveFileAsync();
            using (var stream = await file.OpenStreamForWriteAsync())
            {

                var pixel = await bitmap.GetPixelsAsync();
                var dpi = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi;
                var random = stream.AsRandomAccessStream();
                var jpg = Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId;
                var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(jpg, random);
                var format = Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8;
                var alpha = Windows.Graphics.Imaging.BitmapAlphaMode.Ignore;
                var width = (uint)bitmap.PixelWidth;
                var height = (uint)bitmap.PixelHeight;
                encoder.SetPixelData(format, alpha, width, height, dpi, dpi, pixel.ToArray());
                await encoder.FlushAsync();
            }
            return file;
        }
    }
}
